var express = require('express');
var router = express.Router();
var utils = require('../../functions/utils');


router.get('/' , function(req,res)
{
	var html = "<form name='tmpForm' method='post' action='/renderingObjectList'></form>";
	html +=	"<script language=javascript>tmpForm.submit();</script>";

	res.writeHead(200 , {'Content-Type' : 'text/html; charset=utf-8'});
	res.end(html);

});

function makeRadioDetailTypeString(type)
{
		var str  = '';

		if(type == 'simple')
		{
			str += '<input type="radio" name="detailType" value="simple" checked="checked">SIMPLE';
			str += '<input type="radio" name="detailType" value="detailed">DETAILED';
		}
		else
		{
			str += '<input type="radio" name="detailType" value="simple">SIMPLE';
			str += '<input type="radio" name="detailType" value="detailed" checked="checked">DETAILED';
		}

		return str;
}


function makeSelectObjectTypeString(type)
{
		var str  = '';

		str += "<option  value='all' ";
		if(type == 'all')
			str += "SELECTED ";
		str += ">ALL</option>";

		str += "<option  value='filter' ";
		if(type == 'filter')
			str += "SELECTED ";
		str += ">Filter</option>";

		str += "<option  value='effect' ";
		if(type == 'effect')
			str += "SELECTED ";
		str += ">Effect</option>";

		str += "<option  value='sound' ";
		if(type == 'sound')
			str += "SELECTED ";
		str += ">Sound</option>";

		return str;
}

// 카테고리는 디비에서 읽어온다
function makeSelectObjectCategoryString(type , data)
{
		var str  = '';

		str += "<option  value='all' ";
		if(type == 'all')
			str += "SELECTED ";
		str += ">ALL</option>";


		if(data.length > 0)
		{

			for(var i = 0 ; i < data.length ; i ++)
			{
				str += "<option  value='"+data[i].id+"' ";
				if(type == (data[i].id+'')) // tostring
					str += "SELECTED ";
				str += ">"+data[i].name+"</option>";
			}

		}

		return str;
}

function makeSelectOrderTypeString(type)
{
		var str  = '';

		str += "<option  value='dateDesc' ";
		if(type == 'dateDesc')
			str += "SELECTED ";
		str += ">▼ DATE</option>";

		str += "<option  value='dateAsc' ";
		if(type == 'dateAsc')
			str += "SELECTED ";
		str += ">▲ DATE</option>";

		str += "<option  value='totalCountDesc' ";
		if(type == 'totalCountDesc')
			str += "SELECTED ";
		str += ">▼ TOTAL COUNT</option>";

		str += "<option  value='totalCountAsc' ";
		if(type == 'totalCountAsc')
			str += "SELECTED ";
		str += ">▲ TOTAL COUNT</option>";

		str += "<option  value='rangeCountDesc' ";
		if(type == 'rangeCountDesc')
			str += "SELECTED ";
		str += ">▼ RANGE COUNT</option>";

		str += "<option  value='rangeCountAsc' ";
		if(type == 'rangeCountAsc')
			str += "SELECTED ";
		str += ">▲ RANGE COUNT</option>";

		return str;
}

function makeSelectYearString(year)
{
		var str  = '';
		for(var i = 2014 ; i <= (new Date()).getFullYear() ; i ++)
		{
			if(year == i)
				str += "<option value='" + i + "' SELECTED>"+i+"</option>";
			else
				str += "<option value='" + i + "'>"+i+"</option>";
		}

		return str;
};

function makeSelectMonthString(mon)
{
		var str  = '';
		for(var i = 1 ; i <= 12 ; i ++)
		{
			if(mon == i)
				str += "<option value='" + utils.attachZero(i,2) + "' SELECTED>" + utils.attachZero(i,2) + "</option>";
			else
				str += "<option value='" + utils.attachZero(i,2) + "'>" + utils.attachZero(i,2) + "</option>";
		}

		return str;
};

function makeSelectDayString(day)
{
		var str  = '';
		for(var i = 1 ; i <= 31 ; i ++)
		{
			if(day == i)
				str += "<option value='" + utils.attachZero(i,2) + "' SELECTED>" + utils.attachZero(i,2) + "</option>";
			else
				str += "<option value='" + utils.attachZero(i,2) + "'>" + utils.attachZero(i,2) + "</option>";
		}

		return str;
};


function makeDataSheet(data , detailType , csvFilename)
{

	var str = '<thead><tr bgcolor=#9BDCF2 ><th>&nbsp;<b>NO&nbsp;</th><th><b>ICON</th><th>&nbsp;<b>ID&nbsp;</th><th>&nbsp;<b>CATEGORY&nbsp;</th><th>&nbsp;<b>NAME&nbsp;</th><th>&nbsp;<b>TYPE&nbsp;</th><th>&nbsp;<b>REG_DATE&nbsp;</th>';
	if(detailType == 'detailed')
		str += '<th>&nbsp;<b>VIDEO&nbsp;</th><th>&nbsp;<b>IMAGE&nbsp;</th><th>&nbsp;<b>SOUND&nbsp;</th><th>&nbsp;<b>CURVE&nbsp;</th><th>&nbsp;<b>BLENDING&nbsp;</th><th>&nbsp;<b>OPACITY&nbsp;</th>';
	str += '<th>&nbsp;<b>TOTAL_COUNT&nbsp;</th><th>&nbsp;<b>RANGE_COUNT&nbsp;</th></tr></thead><tbody>';

	var	csv = "\"NO\",\"ID\",\"CATEGORY\",\"NAME\",\"TYPE\",\"REG_DATE\"";
	if(detailType == 'detailed')
		csv += ",\"VIDEO\",\"IMAGE\",\"SOUND\",\"CURVE\",\"BLENDING\",\"OPACITY\"";
	csv += ",\"TOTAL_COUNT\",\"RANGE_COUNT\"";

	var total_sum = 0;
	var range_sum = 0;
	for(var i = 0 ; i < data.length ; i  ++)
	{
		var datestr = data[i].PATH.substr(1,data[i].PATH.length-2);
		datestr = datestr.split("/").join("-"); 

		str += '<tr>';
		str += '<td>&nbsp;'+(i+1)+'&nbsp;</td>';
		str += '<td bgcolor=#000000><img width=60 height=60 src="'+data[i].ICON_URL+'"></td>';
		str += '<td>&nbsp;'+data[i].ID+'&nbsp;</td>';
		str += '<td>&nbsp;'+data[i].CATEGORY+'&nbsp;</td>';
		str += '<td>&nbsp;'+data[i].NAME+'&nbsp;</td>';
		str += '<td><center>'+data[i].TYPE+'</td>';
		str += '<td><center>'+datestr+'</td>';

		if(detailType == 'detailed')
		{
			str += '<td><center>'+data[i].VIDEO+'</td>';
			str += '<td><center>'+data[i].IMAGE+'</td>'; 
			str += '<td><center>'+data[i].SOUND+'</td>';  
			str += '<td><center>'+data[i].CURVE+'</td>';  
			str += '<td><center>'+data[i].BLENDING+'</td>';
			str += '<td><center>'+data[i].OPACITY+'</td>';
		}

		str += '<td>&nbsp;'+data[i].TOTAL_COUNT+'&nbsp;</td>';
		str += '<td>&nbsp;'+data[i].RANGE_COUNT+'&nbsp;</td></tr>';

		csv += "\r\n\""+(i+1)+"\",";
		csv += "\""+data[i].ID+"\",";
		csv += "\""+data[i].CATEGORY+"\",";
		csv += "\""+data[i].NAME+"\",";
		csv += "\""+data[i].TYPE+"\",";
		csv += "\""+datestr+"\",";

		if(detailType == 'detailed')
		{
			csv += "\""+data[i].VIDEO+"\",";
			csv += "\""+data[i].IMAGE+"\","; 
			csv += "\""+data[i].SOUND+"\",";
			csv += "\""+data[i].CURVE+"\",";  
			csv += "\""+data[i].BLENDING+"\",";
			csv += "\""+data[i].OPACITY+"\",";
		}

		csv += "\""+data[i].TOTAL_COUNT+"\",";
		csv += data[i].RANGE_COUNT;

		total_sum += data[i].TOTAL_COUNT;
		range_sum += data[i].RANGE_COUNT;
	}

	str += '<tfoot><tr bgcolor=#CCD9DE>';
	if(detailType == 'detailed')
		str += '<Td colspan=13>';
	else
		str += '<Td colspan=7>';
	str +='<CENTER><b>TOTAL</td><td>&nbsp;'+total_sum+'&nbsp;</td><td>&nbsp;'+range_sum+'&nbsp;</td></tr></tfoot></tbody>';

	//save csv file
	require('fs').writeFile(global.config.storage.statistics.localDirectory + csvFilename, csv, function(err) {
			if(err) throw err;
			console.log('csv File write completed');
		});

	return str;
}


router.post('/', function(req,res)
{
	var sessionKey = req.session.key;

	if(utils.isValidString(sessionKey))
	{
		var async = require('async');
		async.waterfall([
			function(cb)
			{
				utils.checkManagerSession(sessionKey , cb);
			}
			,function(result , cb) 
			{
				// 실패 - 로그인 페이지 
				if(result == 0)
				{
					utils.notifyManagerSessionExpired(req , res);
				}
				// 성공 - 실제 작업코드.
				else
				{	
				/////////////////////////////////////////////////////////////////////////////////////////////	
				/*
					Input parameters 


					objectType
					objectCategory
					orderType

					detailType

					startYear
					startMonth
					startDay
												   
					endYear
					endMonth
					endDay

				*/

					var searchObjectId = req.body.searchObjectId;		
					if(!utils.isValidString(searchObjectId))
						searchObjectId = '';

					var searchObjectName = req.body.searchObjectName;		
					if(!utils.isValidString(searchObjectName))
						searchObjectName = '';

					var objectType = req.body.objectType;		
					if(!utils.isValidString(objectType))
						objectType = 'all';

					var objectCategory = req.body.objectCategory;		
					if(!utils.isValidString(objectCategory))
						objectCategory = 'all';

					var orderType = req.body.orderType;		
					if(!utils.isValidString(orderType))
						orderType = 'rangeCountDesc';

					var detailType = req.body.detailType;		
					if(!utils.isValidString(detailType))
						detailType = 'simple';

					var startYear = req.body.startYear;		
					var startMonth = req.body.startMonth;		
					var startDay = req.body.startDay;		

					var endYear = req.body.endYear;		
					var endMonth = req.body.endMonth;		
					var endDay = req.body.endDay;		

					var db = global.replica_db;

					// 안넘어오면 오늘날짜 첨부터 끝까지 
					if(!utils.isValidString(startYear))
					{
						var today = new Date();
						var ago = new Date();
						ago.setDate(today.getDate() - 14); // 15일 동안.

						startYear = String(ago.getFullYear());
						startMonth = utils.attachZero(ago.getMonth()+1 , 2); //January is 0!
						startDay = utils.attachZero(ago.getDate() , 2);

						endYear = String(today.getFullYear());
						endMonth = utils.attachZero(today.getMonth()+1 , 2); //January is 0!
						endDay = utils.attachZero(today.getDate() , 2);

					}

					var startDate = startYear+'-'+startMonth+'-'+startDay;
					var endDate = endYear+'-'+endMonth+'-'+endDay;


					var fs = require('fs');
					fs.readFile('./template/renderingObjectList' , function(error,data)
					{
						if(error)
						{
							throw error;
						}
						var html = String(data);

						global.log_db.connection.getConnection(function(err,connection)
						{
							if(err)
							{
								throw err;
							}
							
							var input_param = [searchObjectId , searchObjectName , objectType , objectCategory , orderType , detailType , startDate , endDate];

							var sql = 'call manage_getRenderingObjectInfoList(?, ?, ?, ?, ?, ? , ? , ?)';

							var query = connection.query(sql, input_param , function (err, rows) 
							{
								connection.release();
								if(err)
								{
									throw err;
								}

								html = html.split("%SEARCH_OBJECT_ID%").join(searchObjectId); 
								html = html.split("%SEARCH_OBJECT_NAME%").join(searchObjectName); 

								var strSelect = makeSelectObjectTypeString(objectType);
								html = html.split("%OBJECT_TYPE%").join(strSelect); 

								strSelect = makeSelectObjectCategoryString(objectCategory , rows[1]);	// 디비에서 카테고리정보 받아와서..
								html = html.split("%OBJECT_CATEGORY%").join(strSelect); 

								strSelect = makeSelectOrderTypeString(orderType);
								html = html.split("%ORDER_TYPE%").join(strSelect); 

								strSelect = makeRadioDetailTypeString(detailType);
								html = html.split("%DETAIL_TYPE%").join(strSelect); 

								strSelect = makeSelectYearString(Number(startYear));
								html = html.split("%START_YEAR%").join(strSelect); 
								strSelect = makeSelectMonthString(Number(startMonth));
								html = html.split("%START_MONTH%").join(strSelect); 
								strSelect = makeSelectDayString(Number(startDay));
								html = html.split("%START_DAY%").join(strSelect); 

								strSelect = makeSelectYearString(Number(endYear));
								html = html.split("%END_YEAR%").join(strSelect); 
								strSelect = makeSelectMonthString(Number(endMonth));
								html = html.split("%END_MONTH%").join(strSelect); 
								strSelect = makeSelectDayString(Number(endDay));
								html = html.split("%END_DAY%").join(strSelect); 

								var dd = new Date();
								var csvFilename = 'article_'	+ utils.attachZero(dd.getUTCFullYear() , 4) + utils.attachZero(dd.getUTCMonth()+1 , 2) + utils.attachZero(dd.getUTCDate(),2) 
										+ utils.attachZero(dd.getUTCHours(),2) + utils.attachZero(dd.getUTCMinutes(),2)+ utils.attachZero(dd.getUTCSeconds(),2) + '.csv'; 

								// 화면만들고 csv파일만든다.				
								html = html.split("%DATA_SHEET%").join(makeDataSheet(rows[0],detailType , csvFilename));
								// html안의 경로
								html = html.split("%EXCEL_FILENAME%").join(csvFilename);

								res.writeHead(200 , {'Content-Type' : 'text/html; charset=utf-8'});
								res.end(html);

							}); // query

						}); // getConnection

					}); // readfile
			//////////////////////////////////////////////////////////////////////////////////////////

				} // result==1 
			}
		]); //waterfall
	}
	// 암것도 없으면 loginPage
	else
	{
		utils.gotoManagerLoginPage(req , res);
	}
});

module.exports = router;